import traceback

from fastapi import Depends, HTTPException, status

from app.auth.cruds.app_model import AppModelCRUD
from app.auth.models.app_model import AppModelCreate
from app.core.handlers.database import SessionDep
from app.core.handlers.loggers import logger
from app.core.handlers.response import SuccessResponse


class AppModelService:
    def __init__(self, db: SessionDep, app_model_crud: AppModelCRUD = Depends()):
        self.db = db
        self.app_model_crud = app_model_crud

    async def create_app_model(self, app_model_data: AppModelCreate):
        try:
            # 检查是否已存在相同的model_name
            app_model_exist = await self.app_model_crud.get_app_model_by_name(
                app_model_data.model_name
            )
            if app_model_exist:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"AppModel {app_model_data.model_name} 已存在",
                )

            new_app_model = await self.app_model_crud.create_app_model(app_model_data)
            self.db.commit()
            self.db.refresh(new_app_model)
            return SuccessResponse(
                data=new_app_model.model_dump(),
                message="AppModel创建成功",
                code=status.HTTP_201_CREATED,
            )

        except HTTPException:
            # 重新抛出已知的HTTP异常
            raise
        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"发生错误: {str(e)}",
            )
